package com.birdboot.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 该线程任务负责与指定客户端进行一次HTTP交互
 *
 * 1:解析请求
 * 2:处理请求
 * 3:回复响应
 *
 */
public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    public void run() {
        try {
            //1解析请求
            String line = readLine();
            System.out.println(line);
            //请求行相关信息
            String method;
            String uri;
            String protocol;
            //[GET, /index.html, HTTP/1.1]
            String[] data = line.split("\\s");
            method = data[0];
            uri = data[1];
            protocol = data[2];
            System.out.println("method:"+method);//method:GET
            System.out.println("method:"+uri);//uri:/index.html
            System.out.println("method:"+protocol);//protocol:HTTP/1.1

            //读取消息头
            //key:消息头的名字，value:消息头的值
            Map<String,String> headers = new HashMap<>();
            while(true) {
                line = readLine();
                if(line.isEmpty()){//返回值为空串说明单独读取到了空行
                    break;
                }
                System.out.println("消息头:" + line);
                //将消息头按照"冒号空格"拆分并存入到headers中
                //data:[Host, localhost:8088]
                data = line.split(":\\s");
                headers.put(data[0],data[1]);
            }
            System.out.println("headers:"+headers);


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取浏览器发送过来的一行字符串
     * @return
     */
    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();
        //pre:表示上次读取的字符,cur表示本次读取的字符
        char pre='a',cur='a';
        while( (d = in.read()) != -1    ){
            cur = (char)d;//本次读取的字符
            //是否连续读取到了回车+换行
            if(pre==13 && cur==10){
                break;//停止读取,一行已经读取完毕了
            }
            builder.append(cur);//将本次读取的字符拼接
            pre = cur;//在下次读取前,将本次读取的字符记作上次读取的字符
        }
        return builder.toString().trim();
    }
}

